package com.boot.admin.modules.sys.ai.controller;

import com.boot.admin.base.R;
import com.boot.admin.modules.sys.ai.model.query.AiConversationQuery;
import com.boot.admin.modules.sys.ai.model.vo.AiConversationVO;
import com.boot.admin.modules.sys.ai.model.vo.AiMessageVO;
import com.boot.admin.modules.sys.ai.model.vo.StartConversationVO;
import com.boot.admin.modules.sys.ai.service.AiConversationService;
import com.boot.admin.modules.sys.ai.service.RealtimeVoiceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * AI对话管理 - 支持流式传输
 */
@RestController
@RequestMapping("/ai/conversation")
@Tag(name = "AI系统：对话管理（支持实时语音）")
@RequiredArgsConstructor
public class AiConversationController {
    private final AiConversationService aiConversationService;
    private final RealtimeVoiceService realtimeVoiceService;

    /**
     * 开始新对话 - SSE流式响应文本
     */
    @PostMapping("/start")
    @Operation(summary = "开始新对话（SSE流式响应文本）")
    public SseEmitter startConversation(HttpServletRequest request,
                                        @Validated @RequestBody StartConversationVO startVO) {
        String userId = "1298548255977635841";
        return this.aiConversationService.startConversationStreaming(userId, startVO);
    }

    /**
     * 发送文本消息 - SSE流式响应文本
     */
    @PostMapping("/message/text")
    @Operation(summary = "发送文本消息（SSE流式响应文本）")
    public SseEmitter sendTextMessage(HttpServletRequest request,
                                      @RequestParam("conversationId") String conversationId,
                                      @RequestParam("content") String content,
                                      @RequestParam(value = "enableWebSearch", defaultValue = "false") Boolean enableWebSearch) {
        String userId = "1298548255977635841";
        return this.aiConversationService.sendTextMessageStreaming(userId, conversationId, content, enableWebSearch);
    }

    /**
     * 3. 初始化语音消息对话（返回WebSocket连接信息）
     */
    @PostMapping("/message/voice/init")
    @Operation(summary = "初始化语音消息对话（返回WebSocket连接信息）")
    public R<Map<String, Object>> initVoiceMessage(HttpServletRequest request,
                                                   @RequestParam("conversationId") String conversationId) {
        try {
            String userId = "1298548255977635841";

            // 验证对话是否存在且属于用户
            R<AiConversationVO> conversationResult = aiConversationService.getConversationById(userId, conversationId);
            if (!conversationResult.isSuccess()) {
                return R.NG("对话不存在或无权限访问");
            }

            AiConversationVO conversation = conversationResult.getResult();
            if (conversation == null) {
                return R.NG("对话信息获取失败");
            }

            // 初始化实时语音对话状态
            realtimeVoiceService.initConversationState(conversationId, conversation.getRoleId(), userId);

            // 构建WebSocket连接信息
            Map<String, Object> response = new HashMap<>();
            response.put("conversationId", conversationId);
            response.put("roleId", conversation.getRoleId());
            response.put("userId", userId);
            response.put("websocketUrl", buildWebSocketUrl(request, conversationId, conversation.getRoleId(), userId));
            response.put("status", "ready_for_voice");
            response.put("timestamp", System.currentTimeMillis());

            return R.OK(response);

        } catch (Exception e) {
            return R.NG("初始化语音对话失败: " + e.getMessage());
        }
    }

    /**
     * 获取对话列表
     */
    @GetMapping("/list")
    @Operation(summary = "获取对话列表")
    public R<List<AiConversationVO>> getConversationList(@ParameterObject AiConversationQuery query) {
        // 如果没有传userId，使用默认用户ID
        if (query.getUserId() == null || query.getUserId().trim().isEmpty()) {
            query.setUserId("1298548255977635841");
        }

        return aiConversationService.getConversationList(query);
    }

    /**
     * 获取对话消息列表 - 按对话顺序排序
     */
    @GetMapping("/messages/{conversationId}")
    @Operation(summary = "获取对话消息列表（按对话顺序排序）")
    public R<List<AiMessageVO>> getConversationMessages(@PathVariable String conversationId) {
        String userId = "1298548255977635841";
        return aiConversationService.getConversationMessagesSorted(userId, conversationId);
    }

    /**
     * 删除对话
     */
    @DeleteMapping("/{conversationId}")
    @Operation(summary = "删除对话")
    public R<String> deleteConversation(@PathVariable String conversationId) {
        String userId = "1298548255977635841";
        return aiConversationService.deleteConversation(userId, conversationId);
    }

    /**
     * 删除消息
     */
    @DeleteMapping("/message/{messageId}")
    @Operation(summary = "删除消息")
    public R<String> deleteMessage(@PathVariable String messageId) {
        String userId = "1298548255977635841";
        return aiConversationService.deleteMessage(userId, messageId);
    }

    /**
     * 构建WebSocket连接URL
     */
    private String buildWebSocketUrl(HttpServletRequest request, String conversationId, String roleId, String userId) {
        String baseUrl = getBaseUrl(request);
        return String.format("%s/ai/realtime/ws?conversationId=%s&roleId=%s&userId=%s",
                baseUrl.replace("http", "ws"), conversationId, roleId, userId);
    }

    /**
     * 获取基础URL
     */
    private String getBaseUrl(HttpServletRequest request) {
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = request.getServerPort();
        String contextPath = request.getContextPath();

        StringBuilder url = new StringBuilder();
        url.append(scheme).append("://").append(serverName);

        if ((scheme.equals("http") && serverPort != 80) ||
                (scheme.equals("https") && serverPort != 443)) {
            url.append(":").append(serverPort);
        }

        url.append(contextPath);
        return url.toString();
    }
}